<template>
	<view class="pro-body">
	
		<view class="body" >
			<view class="top-container no-bottom-padding">
				<uni-list :border="false" >
					<uni-list-item :border="false" title="单据编号"  :rightText="header.fbillNo" />
					<uni-list-item :border="false" title="生产订单单号"  :rightText="header.fbillnomo" />
					<uni-list-item :border="false" title="创建人"  :rightText="header.fcreateuser" />
					<uni-list-item :border="false" title="入库日期">
						<template v-slot:footer >
							<uni-datetime-picker type="line" v-model="header.fdate" @change="onInStockTimeChange"
								placeholder="请选择入库时间">
							</uni-datetime-picker>
						</template>
					</uni-list-item>		
				</uni-list>
			</view>
			<template v-if="detail && detail.length > 0">
				<view class="" v-for="(item,index) in detail" :key = "index">
					   
					<view class="panel">
						
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">物料编码：</view>
									<view class="panel_content_row_item_value">{{ item.fmaterialnumber }}</view>
								</view>
							</view>
						</view>
						
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">名称：</view>
									<view class="panel_content_row_item_value">{{ item.fmaterialname }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">件号：</view>
									<view class="panel_content_row_item_value">{{ item.fspecification }}</view>
								</view>
								<!-- 暂时没有材质，用单位代替 -->
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">单位：</view>
									<view class="panel_content_row_item_value">{{ item.funitname }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">应收数量：</view>
									<view class="panel_content_row_item_value">{{ item.fmustqty }}</view>
								</view>
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">实收数量：</view>
									<view class="panel_content_row_item_value">{{ item.frealqty }}</view>
								</view>
							</view>
						</view>
						<view class="panel_content" v-if="statusType" >
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">不合格数量：</view>
									
									<view class="panel_content_row_item_value">
										<input v-model="item.unqualityqty"
										placeholder="请输入不合格数量"
										disabled="true"
										placeholder-class="input_placeholder"
										@input="handleQuality(item)"/>
									</view>
							
								</view>
							</view>
						</view>
						<view class="panel_content"  v-if="statusType" >
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">外协不合格数量：</view>
									<view class="panel_content_row_item_value_input">
										<input  v-model="item.outunqualityqty"
										
										placeholder-class="input_placeholder"
										@input="handleQuality(item)"
										/>
									
									</view>
								</view>
							</view>
						</view>
						<view class="panel_content"  v-if="statusType" >
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">废料数量：</view>
									<view class="panel_content_row_item_value">
										<input  v-model="item.failqty"
										disabled="true"
										placeholder-class="input_placeholder"
										/>
									
									</view>
								</view>
							</view>
						</view>
					
			
					</view>
				</view>

			</template>
			
		</view>	
		<!--  底部按钮  -->
		<view class="footerPanel">
			<view class="footerPanel_body">
				<button @click="auditPrdInspect()" class="footerBtn save" :disabled="butClick"><i
						class="iconfont icon-duihao btn_icon" style="font-size: 20px;"></i>审核
				</button>
				
			</view>
		</view>
		<!-- 全局遮罩：在 butClick 为 true 时显示，阻止所有交互，显示转圈提示 -->
		<view v-if="butClick" class="global-mask">
		  <view class="loader-box">
		    <view class="loader"></view>
		    <view class="loader-text">审核中，请稍候...</view>
		  </view>
		</view>
</view>
</template>

<script>
	import uniTransition from 'uni_modules/uni-transition/components/uni-transition/uni-transition.vue';

	import {getProInstosckDetail,
	checkStock,
	auditPrdInspect,
	getLocation
	} from '@/utils/api.js'

	export default {
		components: {
			
		},
		data(){
			return{
				billNo: '',
				loading: true,
				header:{},
				detail:[],
				// isLocation:false,
				materialList : [],
				butClick : false,
				selectRange : [],
				statusType:true,
				inStockTime: '',
	
			}
	},
	methods:{
		formatDateTime(date) {
			const y = date.getFullYear();
			const m = String(date.getMonth() + 1).padStart(2, '0');
			const d = String(date.getDate()).padStart(2, '0');
			const h = String(date.getHours()).padStart(2, '0');
			const min = String(date.getMinutes()).padStart(2, '0');
			const s = String(date.getSeconds()).padStart(2, '0');
			return `${y}-${m}-${d} ${h}:${min}:${s}`;
		},
		getTodayDateTime() {
			return this.formatDateTime(new Date());
		},
		onInStockTimeChange(val) {
			// 有些端返回时间戳或 ISO 格式，这里统一转成 yyyy-MM-dd HH:mm:ss
			if (typeof val === 'string') {
				this.inStockTime = val.length > 19 ? val.slice(0, 19).replace('T', ' ') : val
			} else {
				this.inStockTime = this.formatDateTime(new Date(val))
			}
		},
		handleQuality(e) {
		 let val = e.outunqualityqty;
		 // 第一步：清除非法字符，只保留数字和小数点
		 val = val.toString().replace(/[^0-9.]/g, '');
		 		
		 // 第二步：只保留一个小数点
		 const dotIndex = val.indexOf('.');
		 if (dotIndex !== -1) {
		   val = val.substring(0, dotIndex + 1) + val.substring(dotIndex + 1).replace(/\./g, '');
		 }
		 		
		 // 第三步：限制为最多两位小数
		 if (val.includes('.')) {
		   val = val.replace(/^(\d+)\.(\d{0,2}).*$/, '$1.$2');
		 }
		 		
		 // 第四步：处理前导0（只能是0或者0.xx）
		 if (val.startsWith('0') && !val.startsWith('0.') && val.length > 1) {
		   val = val.replace(/^0+/, '') || '0';
		 }
		 		
		 // 第五步：转为数字用于比较
		 const numeric = parseFloat(val || '0');
		 const mustQty = parseFloat(e.failqty || '0');
		 if (numeric <= mustQty) {
		   // 合法，赋值（保留格式化后的字符串）
		   this.$nextTick(() => {
		     e.outunqualityqty = val || '0';
			 e.unqualityqty = e.failqty - e.outunqualityqty
		   });
		 } else {
		   // 超过上限，提示并置为 0,重置外协不良数量
		   uni.showToast({
		     title: '外协不良数量不能大于废料数量',
		     icon: 'none'
		   });
			e.outunqualityqty = '0';
			this.initData()
		 }
		},


		//扫描仓位，扫描成功后修改下拉框中仓位信息
		scanOrderDe(item) {
			
			let _this = this
			qing.call('scanQRCode', {
			 'needResult': 1, //是否需要处理，默认为0，扫描结果由云之家处理，1则直接返回扫描结果
			 'isShowAlbum': false, //是否显示相册
				success: function(res) {
					if (!item.locationList.includes(res.data.qrcode_str)){
						uni.showToast({
							title:'仓位错误请重试',
							icon:'error'
						})
						return;
					}
					item.locationNo = res.data.qrcode_str
				},
				error: function(e) {
					console.log(e)
			 }
				
			})
		},
		
		
		
		
		//质检生产入库单
		auditPrdInspect(){
			let self = this;

			uni.showModal({
				title:'提示',
				content:'确认审核',
				success(res) {
					if (res.confirm){
						self.butClick = true; // 禁止其他操作
						uni.showLoading({
							title: "审核中...",
							mask: true
						});
						//没启用的话可以直接审核
						auditPrdInspect({header : self.header,
						dataList : self.detail,
						inStockTime : self.inStockTime}).then(result => {
						if (result.data.data){
							uni.showToast({
								title:'审核成功',
								icon:'none'
							})
						}
						uni.hideLoading();
						self.butClick = false;
						setTimeout(() =>{
							uni.navigateBack({
								delta:1,
								success() {
									uni.$emit('update',{msg:'页面刷新'});
								}
							})
						},1000)
						}).catch(err => {
		                    // 接口异常恢复按钮和 loading
		                    uni.hideLoading();
		                    self.butClick = false;
		
		                    uni.showToast({
		                        title: "接口异常，请重新保存",
		                        icon: "error"
		                    });
		
		                    
		                });
					
					}
				}
			})
		},
		
		// 获取详情数据
		initData(){
			getProInstosckDetail({billNo :this.billNo }).then(res => {
				this.header = res.data.data.data
				this.detail = res.data.data.dataList
				this.inStockTime = this.header.fdate || this.getTodayDateTime()
				// this.checkStock()
				this.handleStatus()
			})
		
		
		},
		//判断不合格数量是否允许输入，毛坯和砂芯的不用显示
		handleStatus(){
			if(this.header.fworkshopname === '砂芯车间' || this.header.fworkshopname === '毛胚车间'){
				this.statusType = false
			}
		}
	},
	onLoad(e){
		this.billNo = e.billNo
		// 获取详情数据
		this.initData()
		
	},
	mounted() {
		//引入云之家js
		
		
	}
}
</script>

<style lang="scss" scoped>
	@import "../../static/css/common";
	/* 调整列表项左右文字大小 */
	::v-deep .uni-list-item__content-title {
	    font-size: 22px !important;  /* 左侧标题字体大小 */
		padding-left: 5px;
	}
	::v-deep .uni-list-item__extra-text {
	    font-size: 22px !important;  /* 右侧内容字体大小 */
		padding-right: 5px;
		 color: #333;
	}
	/* 调整行间距 */
	::v-deep .uni-list-item__container {
	    padding: 3px 0 !important;   /* 减小上下内边距 */
	    min-height: 10px !important; /* 减小最小高度 */
	}
	.panel {
	  background: #fbffe2;
	  border-radius: 16rpx;
	  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
	}
	 
	/* 调整标题样式 */
	.panel_content_row_item_title {
	    font-size: 17px !important;  /* 调大字体 */
	    color: #000000 !important;   /* 纯黑字体 */
	    flex-shrink: 0;             /* 防止压缩 */
	}
	/* 调整标题样式 */
	.panel_content_row_item_value {
	  flex: 1;
	  font-size: 17px !important; /* 数值特别放大 */
	  color: #333 !important;
	}
	/* 调整输入框容器 */
	.panel_content_row_item_value_input {
	    flex: 1;                    /* 占据剩余空间 */
	    margin-left: 10px;          /* 增加左右间距 */
	}
	 
	/* 调整输入框本身 */
	.panel_content_row_item_value_input input {
	    height: 40px !important;    /* 调高输入框 */
	    font-size: 18px !important; /* 同步调大输入文字 */
	    // padding: 1px 12px !important;
	    border: 1px solid #ddd;     /* 增加边框更清晰 */
	    border-radius: 4px;
	}
	 
	/* 底部按钮 - 修改布局 */
		.footerPanel {
		  height: 60px;
		  .footerPanel_body {
		    display: flex;
		    justify-content: space-between; /* 左右分布按钮 */
		    width: 100%;
		    padding: 0 10px;
		    box-sizing: border-box;
		    
		    .footerBtn {
		      height: 60px;
		      min-width: 115px;
		      display: flex;
		      line-height: 1;
		      font-size: 30px; /* 适当增大字体 */
		      border-radius: 8px;
		      align-items: center;
		      justify-content: center;
		      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
		      color: #fff;
		      border: none;
		      // margin: 0 10px;
		    }
		  }
		}
	/* 全局遮罩 (覆盖整个页面，挡住所有点击) */
	.global-mask {
	  position: fixed;
	  left: 0;
	  top: 0;
	  right: 0;
	  bottom: 0;
	  z-index: 9999;
	  background: rgba(0,0,0,0.45);
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	/* loader 容器 */
	.loader-box {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  justify-content: center;
	  padding: 20px 30px;
	  background: rgba(255,255,255,0.95);
	  border-radius: 8px;
	}
	
	/* CSS 简易转圈 */
	.loader {
	  width: 44px;
	  height: 44px;
	  border-radius: 50%;
	  border: 4px solid rgba(0,0,0,0.1);
	  border-top-color: #ffffff;
	  border-right-color: #ffffff;
	  animation: spin 1s linear infinite;
	  margin-bottom: 8px;
	}
	
	.loader-text {
	  font-size: 14px;
	  color: #333;
	}
	
	/* 动画 */
	@keyframes spin {
	  from { transform: rotate(0deg); }
	  to { transform: rotate(360deg); }
	}
</style>